<template>
  <div class="department-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>部门管理</span>
          <el-button type="primary" @click="handleAdd">新增部门</el-button>
        </div>
      </template>
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="序号" min-width="15%" align="center" />
        <el-table-column prop="name" label="部门名称" min-width="35%" align="center" />
        <el-table-column prop="updateTime" label="最后操作时间" min-width="35%" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="15%" align="center">
          <template #default="scope">
            <el-button 
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button 
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门编号" prop="id" v-if="form.id">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getDepartmentList,
  deleteDepartment,
  addDepartment,
  updateDepartment
} from '@/api/department'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  id: '',
  name: '',
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 获取部门列表
const fetchDepartmentList = async () => {
  try {
    loading.value = true
    const res = await getDepartmentList()
    tableData.value = res.data || []
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error(error.message || '获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 新增部门
const handleAdd = () => {
  dialogTitle.value = '新增部门'
  form.value = {
    id: '',
    name: '',
  }
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (row) => {
  dialogTitle.value = '编辑部门'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该部门吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await deleteDepartment(row.id)
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchDepartmentList()
      }
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.value.id) {
          // 编辑
          res = await updateDepartment(form.value)
        } else {
          // 新增
          res = await addDepartment(form.value)
        }
        
        if (res.code === 1) {
          ElMessage.success(form.value.id ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchDepartmentList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchDepartmentList()
})
</script>

<style scoped>
.department-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-button--text) {
  margin-right: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}
</style> 